/**
 * @date: 2025/3/22
 * @author: 小红
 * @fileName: useEnv
 * @Description: 获取环境变量
 */

/**
 * 环境变量
 * @param envConf
 * @param node
 */
export function wrapperEnv(envConf: Recordable = import.meta.env, node?: boolean): ViteEnv {
  const ret: any = {}

  for (const envName of Object.keys(envConf)) {
    let realName =
      typeof envConf[envName] == 'string'
        ? envConf[envName].replace(/\\n/g, '\n')
        : envConf[envName]
    realName = realName === 'true' ? true : realName === 'false' ? false : realName

    if (envName === 'VITE_PORT') {
      realName = Number(realName)
    }
    ret[envName] = realName

    if (node) {
      if (typeof realName === 'string') {
        process.env[envName] = realName
      } else if (typeof realName === 'object') {
        process.env[envName] = JSON.stringify(realName)
      }
    }
  }
  return ret
}

const env = wrapperEnv()

/**
 * 获取环境变量
 * @param key
 * @param fn
 */
export function useEnv(key: keyof ViteEnv, fn?: (key: any) => any) {
  if (fn) {
    return fn(env?.[key])
  }

  return env?.[key]
}
